import { defineStore } from "pinia";
const dayjs = useDayjs();
interface State {
  timmer:  Set<number>;
  timeUnix: number;
  lastTime: string;

}
const defaultState: State = {
    timmer: new Set(),
    timeUnix: dayjs().unix(),
    lastTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
};

export default defineStore("time", {
  state: () => defaultState,
  getters: {
    getTimer: (state) => {
      return state.timmer;
    },
    getLastTime: (state) => {
      return state.lastTime;
    }
  },
  actions: {
    render(callBack?: (callBackList?:any[]) => void) {
      let fps = 60;
      let fpsInterval = 1000 / fps;
      let last = ref<number>(new Date().getTime()); //上次执行的时刻

      let callBackList: (((callBackList?: any[]) => void) | undefined)[]=[]
      if(callBackList){
        callBackList.push(callBack)
      }
      let ID:any=0
      const animate = () => {
        // 动画逻辑...
        ID = requestAnimationFrame(animate as any);
        this.timmer.add(ID)
        // 执行时的时间
        var now: number = dayjs().valueOf() ;
        var elapsed = now - last.value;
        // 经过了足够的时间 17ms
        if (elapsed > fpsInterval) {        
          last.value = now - (elapsed % fpsInterval); //校正当前时间
          this.timeUnix=now - (elapsed % fpsInterval);
          this.lastTime=dayjs(last.value).format("YYYY-MM-DD HH:mm:ss")
          // lastTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss');
          // 任务队列
          // while(callBackList.length>0){
          //   callBackList[0]!()
          //   callBackList.shift()
          // }

          callBack!()

        }
      }
      animate();
  
    },
  },
  // persist: {
  //     enabled: true,
  //     strategies: [
  //         {
  //             key: 'alarm',   //存储了所有变量
  //             storage: localStorage
  //             // paths: ['message', 'content', 'isFirst']
  //         }
  //         // {storage: sessionStorage, paths: ['message']},
  //         // {storage: localStorage, paths: ['content']}
  //     ]
  //   }
});
